package com.managertrade.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableJpaRepositories(
        basePackages = "com.managertrade.dao.sqlite.repository",  // SQLite 的 Repository 包
        entityManagerFactoryRef = "sqliteEntityManagerFactory",
        transactionManagerRef = "sqliteTransactionManager"
)
@Slf4j
public class SqliteConfig {

    @Value("${spring.datasource.sqlite.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.sqlite.url}")
    private String url;

    @Bean(name = "sqliteDataSource")
    public DataSource sqliteDataSource() {
        try {
            // 如果想自动创建目录，可以解析一下 db 文件路径
            if (url.startsWith("jdbc:sqlite:")) {
                String path = url.substring("jdbc:sqlite:".length());
                File dbFile = new File(path);
                if (!dbFile.isAbsolute()) {
                    // 转成相对于 jar 所在目录的绝对路径
                    File jarDir = new File(System.getProperty("user.dir")); // 当前启动目录
                    dbFile = new File(jarDir, path);
                }
                File parentDir = dbFile.getParentFile();
                log.info("数据目录{}",parentDir.getAbsolutePath());
                if (!parentDir.exists()) parentDir.mkdirs();
            }


            return DataSourceBuilder.create()
                    .driverClassName(driverClassName)
                    .url(url)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException("Failed to create SQLite DataSource", e);
        }
    }

    @Bean(name = "sqliteEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean sqliteEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("sqliteDataSource") DataSource dataSource) {
        Map<String, Object> props = new HashMap<>();
        props.put("hibernate.dialect", "com.managertrade.config.SQLiteDialect");
        props.put("hibernate.hbm2ddl.auto", "none");
        return builder
                .dataSource(dataSource)
                .packages("com.managertrade.dao.sqlite.entity")
                .persistenceUnit("sqlitePU")
                .properties(props)
                .build();
    }

    @Bean(name = "sqliteTransactionManager")
    public JpaTransactionManager sqliteTransactionManager(
            @Qualifier("sqliteEntityManagerFactory") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

}
